package dyy.zc.computergradeexam.ui.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import dyy.zc.computergradeexam.R;
import dyy.zc.computergradeexam.application.MyApplication;
import dyy.zc.computergradeexam.base.BaseActivity;
import dyy.zc.computergradeexam.bean.ChooseInfo;
import dyy.zc.computergradeexam.bean.WrongQuestion;
import dyy.zc.computergradeexam.utils.AppManager;
import dyy.zc.computergradeexam.utils.BmobUtils;
import dyy.zc.computergradeexam.utils.ToastUtils;
import dyy.zc.computergradeexam.views.EmptyView;
import dyy.zc.computergradeexam.views.MyAlertDialog;

public class XuanZeActivity extends BaseActivity implements View.OnClickListener {
    private TextView title,right;
    private ScrollView scrollView;
    private RelativeLayout rl_right;
    private TextView tvQuestion;
    private TextView[] answer = new TextView[4];//答案
    private int[] answerID = {R.id.tv_Answer_A,R.id.tv_Answer_B,R.id.tv_Answer_C,R.id.tv_Answer_D};
    private LinearLayout[] ll_select = new LinearLayout[4];//选择一行
    private int[] ll_selectID = {R.id.select_A,R.id.select_B,R.id.select_C,R.id.select_D};
    private boolean[] choose = {false,false,false,false};//标记选择的哪一个
    private TextView tvShowAnswer,correct;
    private LinearLayout llAnswerArea;
    private List<ChooseInfo> list = new ArrayList<>();
    private List<ChooseInfo> wronglist = new ArrayList<>();
    public WrongQuestion wrongQuestion;
    private List<String> wrongIdS = new ArrayList<>();
    private boolean checkWrong = false;
    private boolean isHas = false;
    private ChooseInfo chooseInfo;
    private BmobUtils bmobUtils;
    private EmptyView emptyView;
    private int count = 0;//标记第几题
    private int correctAnswer = -1;//标记正确答案是第几个
    private final int SUCCESS = 1;
    private boolean tick = true;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SUCCESS://选择题获取完成
                    if (checkWrong){//展示错题
                        if (wrongQuestion == null||wrongQuestion.getId().size()==0){
                            emptyView.setNotify("暂无错题");
                        }else {
                            wrongIdS.clear();
                            wrongIdS.addAll(wrongQuestion.getId());
                            for (ChooseInfo chooseInfo:list){
                                for (String id:wrongIdS){
                                    if (chooseInfo.getObjectId().equals(id)){
                                        wronglist.add(chooseInfo);
                                    }
                                }
                            }
                            scrollView.setVisibility(View.VISIBLE);
                            setQuestions();
                        }
                    }else {
                        if (wrongQuestion == null){
                            isHas = false;
                            wrongQuestion = new WrongQuestion();
                            wrongQuestion.setType("1");
                            wrongQuestion.setAccount(loginuser.getAccount());
                            wrongQuestion.setId(wrongIdS);
                        }else {
                            wrongIdS.clear();
                            wrongIdS.addAll(wrongQuestion.getId());
                            isHas = true;
                        }
                        scrollView.setVisibility(View.VISIBLE);
                        setQuestions();
                    }
                    dialog.dismiss();
                    break;
                case 2://加载下一题
                    resetImg();
                    for(int i = 0;i<4;i++) {//重置正确选项
                        choose[i] = false;
                    }
                    setQuestions();
                    tick = true;
                    break;
                case 3://没有下一题
                    ToastUtils.shortToast(XuanZeActivity.this,"已经是最后一题啦~~~");
                    break;
                case 4://保存错题
                    dialog.dismiss();
                    finish();
                    break;
            }
        }
    };

    /**
     * 设置题目
     */
    public void setQuestions(){
        if (checkWrong) {
            chooseInfo = wronglist.get(count);
        }else {
            chooseInfo = list.get(count);
            correctAnswer = getCorrectAnswer(chooseInfo.getAnswer().split("：")[1]);
            choose[correctAnswer] = true;
        }
        tvQuestion.setText((count+1)+"、"+chooseInfo.getQuestion());
        answer[0].setText(chooseInfo.getAnswerA());
        answer[1].setText(chooseInfo.getAnswerB());
        answer[2].setText(chooseInfo.getAnswerC());
        answer[3].setText(chooseInfo.getAnswerD());
        correct.setText(chooseInfo.getAnswer());
    }

    @Override
    protected void findViewByIDS() {
        emptyView = new EmptyView(this);
        title = (TextView) findViewById(R.id.top_tv_title);
        scrollView = findViewsById(R.id.scrollView);
        right = (TextView) findViewById(R.id.top_tv_right);
        rl_right = findViewsById(R.id.top_rl_right);
        tvQuestion = (TextView) findViewById(R.id.tv_question);
        tvShowAnswer = (TextView) findViewById(R.id.tv_ShowAnswer);
        llAnswerArea = (LinearLayout) findViewById(R.id.ll_AnswerArea);
        correct = (TextView) findViewById(R.id.tv_Answer);
        for (int i=0;i<4;i++){
            answer[i] = findViewsById(answerID[i]);
            ll_select[i] = findViewsById(ll_selectID[i]);
        }

    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xuan_ze);
        initData();
        bind();
    }

    private void bind() {
        rl_right.setOnClickListener(this);


        if (!checkWrong) {
            tvShowAnswer.setOnClickListener(this);
            for (int i=0;i<4;i++){
                ll_select[i].setOnClickListener(selectListener);
            }
        }

    }


    // 捕获返回键的方法1
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        && event.getRepeatCount() == 0
        if (checkWrong) {//去掉返回的弹窗
            finish();
        } else {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                // 按下BACK，同时没有重复
                back();
            }
        }

        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void backClick(View view) {
        if (checkWrong){
            finish();
        }else {
            back();
        }

    }

    public void back(){
        if (count >= list.size()){
            saveWrong();
        }else {
            MyAlertDialog logDialog = new MyAlertDialog(this);
            logDialog.builder()
                    .setTitle("退出提示")
                    .setMsg("题目还没有做完呢")
                    .setNegativeButton("火大不做了", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            saveWrong();
                        }
                    })
                    .setPositiveButton("开个玩笑", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                        }
                    })
                    .show();
        }
    }

    /**
     * 保存错题
     */
    public void saveWrong(){
        dialog = ProgressDialog.show(this,null,"正在保存错题");
        wrongQuestion.setId(wrongIdS);
        if (isHas){

            bmobUtils.updateWrongQuestion(wrongQuestion,4,handler);
        }else {

            bmobUtils.saveWrongQuestion(wrongQuestion,4,handler);
        }
    }

    private View.OnClickListener selectListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (tick){
                for(int i = 0;i<4;i++){
                    if (v.getId() == ll_selectID[i]){
                        check(i);
                    }
                }
            }

        }
    };

    public void check(int i){
        tick = false;
        resetImg();
        if (choose[i]){//判断是否选择的是正确答案
            answer[i].setTextColor(getResources().getColor(R.color.colorWhite));
            ll_select[i].setBackgroundColor(getResources().getColor(R.color.colorBlue));
            count++;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (count < list.size()){
                        handler.sendEmptyMessage(2);
                    }else {
                        handler.sendEmptyMessage(3);
                    }
                }
            }).start();

        }else {
            answer[i].setTextColor(getResources().getColor(R.color.colorWhite));
            ll_select[i].setBackgroundColor(getResources().getColor(R.color.colorRed));
            rl_right.setVisibility(View.VISIBLE);
            right.setVisibility(View.VISIBLE);
            tvShowAnswer.setVisibility(View.VISIBLE);

            String id = list.get(count).getObjectId();
            if (!wrongIdS.contains(id)){//添加错误题目
                wrongIdS.add(id);
            }
        }
    }

    /**
     * 重置颜色
     */
    private void resetImg() {
        for(int i = 0;i<4;i++){
            answer[i].setTextColor(getResources().getColor(R.color.colorBlack));
            ll_select[i].setBackgroundColor(getResources().getColor(R.color.colorWhite));
        }
    }

    public int getCorrectAnswer(String s){
        int i = 0;
        switch (s){
            case "A":i = 0;break;
            case "B":i = 1;break;
            case "C":i = 2;break;
            case "D":i = 3;break;
        }
        return i;
    }

    private void initData() {
        bmobUtils = new BmobUtils(this);
        right.setText("下一题");
        scrollView.setVisibility(View.GONE);
        dialog = ProgressDialog.show(this,null,"正在加载题目......");
        bmobUtils.getChooseInfo(loginuser.getAccount(),"1",list,SUCCESS,handler);
        Intent intent = getIntent();
        if (intent.getIntExtra("type",0)==1){//展示错题
            checkWrong = true;
            title.setText("我的错题");
            tvShowAnswer.setVisibility(View.VISIBLE);
            llAnswerArea.setVisibility(View.VISIBLE);
            rl_right.setVisibility(View.VISIBLE);
            right.setVisibility(View.VISIBLE);
        }else {
            title.setText("查看题目");
            checkWrong = false;
            tvShowAnswer.setVisibility(View.GONE);
            rl_right.setVisibility(View.GONE);
        }

        //读取raw资源文件获得一个InputStream用来读取文件用的
        //这个只要获取一次
//        InputStream inputStream = getResources().openRawResource(R.raw.xuanze);
//        getString(inputStream);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_ShowAnswer:
                llAnswerArea.setVisibility(View.VISIBLE);
                break;
            case R.id.top_rl_right:
                count++;
                    if (!checkWrong) {
                        if (count < list.size()){
                            resetImg();
                            rl_right.setVisibility(View.GONE);
                            right.setVisibility(View.GONE);
                            llAnswerArea.setVisibility(View.GONE);
                            tvShowAnswer.setVisibility(View.GONE);
                            tick = true;
                            setQuestions();
                        }else {
                            ToastUtils.shortToast(XuanZeActivity.this,"已经是最后一题啦~~~");
                        }
                    }else {
                        if (count < wronglist.size()) {
                            setQuestions();
                        } else {
                            ToastUtils.shortToast(XuanZeActivity.this, "已经是最后一题啦~~~");
                        }
                    }
                break;
        }
    }
//    public void getString(InputStream inputStream) {
//        //将InputStream转换成inputStreamReader并设置读取的编码格式utf-8
//        InputStreamReader inputStreamReader = null;
//        try {
//            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
//        } catch (UnsupportedEncodingException e1) {
//            e1.printStackTrace();
//        }
//        //再将InputStreamReader封装成BufferedReader
//        BufferedReader reader = new BufferedReader(inputStreamReader);
//        //申明字符串，用来保存读取的数据
//        StringBuffer sb = new StringBuffer("");
//        //这个是申明读取的行数，一般都是循环读取的，你把删掉了。。。。。
//        //当后面没有数据之后，line会返回null，根据这个判断是不是读取到文本末尾了
//        String line;
//        String first = null;
//        String QUES= null;
//        try {
//             first = URLEncoder.encode("Q","utf-8");
//             QUES = URLEncoder.encode("W","utf-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        boolean over = false;
//        chooseInfo = new ChooseInfo();
//        sb.setLength(0);
//        int count = 0;
//        try {
//
//            //一般是这样的，读一行就添加一行到字符串末尾
//            while ((line = reader.readLine()) != null) {
//                if (line.equals(first)){
//                    if (over){
//                        chooseInfoList.add(chooseInfo);
////                        Log.e("Question",chooseInfo.getQuestion());
//                        over = false;
//
//                    }
////                    Log.e("line",line);
//                    chooseInfo = new ChooseInfo();
//                    sb.setLength(0);
//                }else if(line.equals(QUES)){
//                    chooseInfo.setQuestion(String.valueOf(sb));
//                    sb.setLength(0);
//                    count = 1;
//                }else {
//                    switch (count){
//                        case 0:
//                            sb.append(line);
//                            break;
//                        case 1:
//                            chooseInfo.setAnswerA(line);
//                            sb.setLength(0);
//                            count = 2;
//                            break;
//                        case 2:
//                            chooseInfo.setAnswerB(line);
//                            sb.setLength(0);
//                            count = 3;
//                            break;
//                        case 3:
//                            chooseInfo.setAnswerC(line);
//                            sb.setLength(0);
//                            count = 4;
//                            break;
//                        case 4:
//                            chooseInfo.setAnswerD(line);
//                            sb.setLength(0);
//                            count = 5;
//                            break;
//                        case 5:
//                            chooseInfo.setAnswer(line);
//                            sb.setLength(0);
//                            count = 0;
//                            over = true;
//                            break;
//                    }
//                }
////                switch (line){
////                    case "quse":
////                        Log.e("line",line);
////                        if (over){
////                            chooseInfoList.add(chooseInfo);
////                            Log.e("Question",chooseInfo.getQuestion());
////                            over = false;
////                        }
////                        Log.e("line",line);
////                        chooseInfo = new ChooseInfo();
////                        sb.setLength(0);
////                        break;
////                    case "@":
////                        chooseInfo.setQuestion(String.valueOf(sb));
////                        sb.setLength(0);
////                        count = 1;
////                        break;
////                    default:
////
////                        break;
////                }
//
//            }
//
//            //这个是读取一行的
////            line = reader.readLine();
////            //将读取的一行加入字符串末尾
////            sb.append(line);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

}
